package com.yonyou.cyxdms.sysAuth.service.utill;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

public class RequestUtils {

    private final static Logger log = LoggerFactory.getLogger(RequestUtils.class);

    private final static String DEFAULT_TOKEN_HEADER_NAME = "Authorization";
    private final static String BEARER_TOKEN = "Bearer ";

    public static String getTokenFromHeader(HttpServletRequest request) {
        return getTokenFromHeader(request, DEFAULT_TOKEN_HEADER_NAME);
    }

    public static String getTokenFromHeader(HttpServletRequest request, String headerName) {
        String accessToken = request.getHeader(headerName);
        if (accessToken == null || !accessToken.startsWith(BEARER_TOKEN)) {
            return null;
        }
        log.debug("getting accessToken from header orgin: " + accessToken);
        String accessTokenAfterSubstr = accessToken.substring(BEARER_TOKEN.length());
        log.debug("getting accessToken from header after substring: " + accessTokenAfterSubstr);
        return accessTokenAfterSubstr;
    }

    public static String getTokenFromUrl(HttpServletRequest request) {
        return getTokenFromUrl(request, DEFAULT_TOKEN_HEADER_NAME);
    }

    public static String getTokenFromUrl(HttpServletRequest request, String headerName) {
        String accessToken = request.getParameter(headerName);
        log.debug("getting accessToken from url: " + accessToken);
        return accessToken;
    }
    
    public static String getItemFromHeader(HttpServletRequest request, String headerName) {
        String item = request.getHeader(headerName);
        log.debug("getting item from header: " + item);
        return item;
    }
}
